package com.example.demo.Service;

import com.alibaba.fastjson.JSON;
import com.example.demo.Mappers.GetRecipeListMapper;
import com.example.demo.Mappers.RegistMapper;
import com.example.demo.beans.*;
import com.example.demo.utils.AppConfigUtils;
import com.example.demo.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**执行缴费
 * 诊间缴费
 * Created by Administrator on 2018-05-08.
 */
@Service("PayBillTradeService")
@Transactional(readOnly =true)
public class PayBillTradeService {
    @Autowired
    private RegistMapper registMapper;
    @Autowired
    private GetRecipeListMapper mapper;
    private Logger logger = LoggerFactory.getLogger(PayBillTradeService.class);
    public PayBillTradeResponse  PayBill(PayBillTradeRequest request){
        logger.error("诊间缴费入参："+ JSON.toJSONString(request));
        PatientInfodetail d=registMapper.selectpatientdetal(request.getPatientID(),request.getCardNo());
       if(d==null){
       PayBillTradeResponse response=new PayBillTradeResponse();
       response.setResultCode("1");
       response.setResultMsg("提示:获取到的病人信息为空，请检查！");
       logger.error("诊间出参："+"出错序号："+request.getRegID()+JSON.toJSONString(response));
       return response;
       }
        String czybm= AppConfigUtils.getGhybm();
       String czyxm=AppConfigUtils.getCzyxm();
        String czyks=AppConfigUtils.getGhyks();
        String ywckbm=AppConfigUtils.getYwckbm();
        String brid=request.getPatientID();
        String ylkh=request.getCardNo();
        String jsjlid="";

        Long tempyyghid=Long.parseLong(DateUtils.getStringToday()+"000000");

        List<GetRecipeListItem3> item3s=new ArrayList<>();
        //获取处方信息
        item3s =mapper.selectRecipe1(request.getRegID());
       //交易总费用用来判断是否与输入费用相等
       double fy=0;
     double fy1=Double.valueOf(request.getPayAmt());
        for(int m=0;m<item3s.size();m++){
            fy=Double.valueOf(item3s.get(m).getRecipeAmount())+fy;
        }
        if(!(fy1-fy>=-0.05&&fy1-fy<=0.05)){
            PayBillTradeResponse r=new PayBillTradeResponse();
            r.setResultCode("1");
            r.setResultMsg("交易成功，但是交易金额与实际应收金额相差大于0.1元，请核实或者到收费窗口处理,实际费用应为"+fy+"元");
            logger.error("诊间出参："+"出错序号："+request.getRegID()+JSON.toJSONString(r));
            return  r;
        }
        //获取门诊费用表中未收费处方金额用来判断应缴费金额是否一致
        String tempfy2=mapper.getnotPaymony(request.getRegID());
        double fy2=0;
        fy2=Double.valueOf(tempfy2);
        if(!(fy1-fy2>=-0.05&&fy1-fy2<=0.05)){
            PayBillTradeResponse r2=new PayBillTradeResponse();
            r2.setResultCode("1");
            r2.setResultMsg("交易成功，但是交易金额与门诊费用表总金额相差大于0.1元，请核实或者到收费窗口处理！");
            return  r2;
        }
//        System.out.print(item3s.get(0).getDoctName());
        Jsjl_YwxhBean jsjl_ywxhBean=registMapper.getJsjlywxh();
        String jsxh=jsjl_ywxhBean.getXh();
        int i= DateUtils.daysBetween(jsjl_ywxhBean.getSsrq());
        if(i>=1){
            jsjlid =ifithanone(tempyyghid,request.getRegID().trim(),czybm,ywckbm,brid,czyks,ylkh,request.getPayAmt().trim());
        }
        else {jsjlid=ifilessone(tempyyghid,request.getRegID().trim(),czybm,ywckbm,brid,czyks,ylkh,jsxh,request.getPayAmt().trim());}
        List<GetRecipeListItem2> item2s=new ArrayList<>();
        for (int k=0;k<item3s.size();k++){

            List<GetRecipeListtem1> listtem1s=new ArrayList<>();
            registMapper.updatesfysghf(item3s.get(k).getGhxh());
            listtem1s=mapper.selectdetailRecipe(item3s.get(k).getGhxh(),item3s.get(k).getYzlx());
            GetRecipeListItem2 item2=new GetRecipeListItem2(listtem1s,item3s.get(k).getDeptID(),
                    item3s.get(k).getDeptName(),item3s.get(k).getDoctName(),item3s.get(k).getRecipeID(),item3s.get(k).getRecipeName(),item3s.get(k).getRecipeType(),item3s.get(k).getRecipeAmount(),item3s.get(k).getExecDept(),item3s.get(k).getExecLocation(),item3s.get(k).getRecipeDate(),item3s.get(k).getExecDate(),item3s.get(k).getNote());
            item2s.add(item2);
            //门诊发票信息
            MzdqpjBean mzdqpjBean=registMapper.Getmzpjxx(czybm);
            String qshnew=String.valueOf(Long.valueOf(mzdqpjBean.getQsh())+1);
            registMapper.updatemzdqqj(qshnew,mzdqpjBean.getQsh(),mzdqpjBean.getJsh(),mzdqpjBean.getFpjlid(),czybm);

    mapper.Updatemzb_brfy(czybm,DateUtils.Getdnowdatexx(),qshnew,jsjlid,item3s.get(k).getGhxh(),item3s.get(k).getYzlx());
      if(item3s.get(k).getYzlx().trim().equals("2")){
          mapper.Updateyfb_ypcf(czybm,DateUtils.Getdnowdatexx(),item3s.get(k).getGhxh());
      }
else if(item3s.get(k).getYzlx().trim().equals("3"))
{mapper.UpdateMzysjcsq(czybm,DateUtils.Getdnowdatexx(),item3s.get(k).getGhxh());}
      else if(item3s.get(k).getYzlx().trim().equals("4"))
      {mapper.UpdateMzysjysq(czybm,DateUtils.Getdnowdatexx(),item3s.get(k).getGhxh());}
      else if(item3s.get(k).getYzlx().trim().equals("5"))
      {mapper.UpdateMzyszlcz(czybm,DateUtils.Getdnowdatexx(),item3s.get(k).getGhxh());}
 else {mapper.UpdateMzysmzss(czybm,DateUtils.Getdnowdatexx(),item3s.get(k).getGhxh());}
        }
        PayDetailBean pa=setPayBean(d,jsjlid,request,czybm,czyxm);
        registMapper.saverePaybean(pa);
        String traID=mapper.gethostraID(request.getPatientID());
        PayBillTradeResponse response=new PayBillTradeResponse();
        response.setResultCode("0");
        response.setResultMsg("交易成功！");
        response.setHosTranNo(traID);
        response.setRecipes(item2s);
        logger.error("诊间正常出参："+JSON.toJSONString(response));
        return response;
    }


    /**
     * 当结算记录业务序号时间大于1时执行
     * @param tempjsjlid
     * @param ghxh
     * @param czybm
     * @param ywckbm
     * @param brid
     * @param czyks
     * @param ylkh
     * @return
     */
    private String  ifithanone(Long tempjsjlid,String ghxh,String czybm,String ywckbm,String brid,String czyks,String ylkh,String fyhj){
        registMapper.updejsjlywxh("000001",DateUtils.Getdnowdatexx());
        String jsjlid=String.valueOf(tempjsjlid+1);
        JsjlBean jsjlBean=new JsjlBean(jsjlid,ghxh,"1",czybm,ywckbm,brid,fyhj,"0",
                fyhj,"0","0","0" ,"0","0",DateUtils.Getdnowdatexx(),czyks,
                "诊间缴费结算","","0","0","0",ylkh,"0",
                "0","0","0");
        registMapper.saveghjsb(jsjlBean);
        return  jsjlid;
    }

    private String  ifilessone(Long tempjsjlid,String ghxh,String czybm,String ywckbm,String brid,String czyks,String ylkh,String xh,String fyhj){
        int xh1 = Integer.parseInt(xh.trim()) + 1;
        String xh2=registMapper.selectywxhbyid(xh1).getXh();
        registMapper.updejsjlywxh(xh2,DateUtils.Getdnowdatexx());
        String jsjlid=String.valueOf(tempjsjlid+xh1);
        JsjlBean jsjlBean=new JsjlBean(jsjlid,ghxh,"1",czybm,ywckbm,brid,fyhj,"0",
                fyhj,"0","0","0" ,"0","0",DateUtils.Getdnowdatexx(),czyks,
                "诊间缴费结算","","0","0","0",ylkh,"0",
                "0","0","0");
        registMapper.saveghjsb(jsjlBean);
        return  jsjlid;
    }

    private  PayDetailBean setPayBean(PatientInfodetail pa,String jsxh,PayBillTradeRequest r,String czybm,String czyxm){
        PayDetailBean pay=new PayDetailBean();
        pay.setBzms("微信诊间结算");
        pay.setPayTag(r.getPayTag());
        pay.setCodeTermidNo(r.getCodeTermidNo());
        pay.setPayTranDate(r.getPayTranDate());
        pay.setAddress(pa.getAddress());
        pay.setAutoTranNo(r.getAutoTranNo());
        pay.setBankCardNo(r.getBankCardNo());
        pay.setBankPNo(r.getBankPNo());
        pay.setBankReferNo(r.getBankReferNo());
        pay.setBankTermid(r.getBankTermid());
        pay.setBirthday(pa.getBirthday());
        pay.setCardType(r.getCardType());
        pay.setCodeBuyerAccount(r.getCodeBuyerAccount());
        pay.setBankTranNo(r.getBankTranNo());
        pay.setJsxh(jsxh);
        pay.setCodeTradeOrderNo(r.getCodeTradeOrderNo());
        pay.setMobile(pa.getMobile());
        pay.setName(pa.getName());
        pay.setPayAmt(r.getPayAmt());
        pay.setIDCardNo(pa.getIDCardNo());
        pay.setSex(pa.getSex());
        pay.setUserId(r.getUserID());
        pay.setPayTranTime(r.getPayTranTime());
        pay.setCardNo(r.getCardNo());
        pay.setPatientID(pa.getPatientID());
        pay.setReqtype(r.getReqtype());
        pay.setCzybm(czybm);
        pay.setCzyxm(czyxm);
        return  pay;
    }
}
